package cn.edu.tsinghua.cic.ccss.bo.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.forten.core.dao.rdb.hibernate.HibernateDao;
import org.forten.core.dao.rdb.query.parameter.Param;
import org.forten.core.dao.rdb.query.parameter.Type;
import org.forten.utils.common.DateUtil;
import org.forten.utils.security.UrlCodeUtil;
import org.forten.utils.system.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.tsinghua.cic.ccss.bo.CoursewareBo;
import cn.edu.tsinghua.cic.ccss.dto.CoursewareDto;
import cn.edu.tsinghua.cic.ccss.entity.Courseware;

@Service("coursewareBo")
public class CoursewareBoImpl implements CoursewareBo {
	private static Logger log = Logger.getLogger(CoursewareBoImpl.class);
	@Resource(name = "hibernateDao")
	private HibernateDao hibernateDao;

	@Override
	@Transactional
	public List<CoursewareDto> findCoursewareByCourseId(Long courseId) {

		String hql = "select id,wareName,czsj,fileSize from Courseware where courseId=:courseId";
		Object[] wareContents = hibernateDao.findObjectArray(hql,
				Param.getCommonParam("courseId", courseId, Type.LONG));
		List<CoursewareDto> dtos = new ArrayList<CoursewareDto>(
				wareContents.length);
		for (Object wareContent : wareContents) {
			Object[] objArr = (Object[]) wareContent;
			CoursewareDto dto = new CoursewareDto();
			dto.setId((Long) objArr[0]);
			dto.setWareName((String) objArr[1]);
			dto.setCzsj((String) objArr[2]);
			dto.setFileSize((String) objArr[3]);
			dtos.add(dto);
		}
		return dtos;
	}

	@Override
	@Transactional
	public void doDeleteCourseware(Long id) {
		Courseware entity = hibernateDao.load(Courseware.class, id);
		LogUtil.info(log, "于%s删除课件信息", DateUtil.convertDateToString(new Date()));
		hibernateDao.delete(entity);
	}

	@Override
	@Transactional
	public void doSaveCourseware(Courseware entity) {
		hibernateDao.save(entity);
	}

	@Override
	public boolean checkFileType(String filename) {
		
		String suffix = getExtensionName(filename).toLowerCase(Locale.ENGLISH);
		
		if (suffix.endsWith("pdf") || suffix.endsWith("xlsx")
				|| suffix.endsWith("xls") || suffix.endsWith("docx")
				|| suffix.endsWith("pptx") || suffix.endsWith("doc") || suffix.endsWith("ppt")
				|| suffix.endsWith("zip") || suffix.endsWith("rar")) {
			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public byte[] downloadCoursewareById(Long id, HttpServletResponse response) {
		Courseware entity = hibernateDao.get(Courseware.class, id);
		if (entity == null) {
			return new byte[0];
		}
		String wareName = entity.getWareName();
		String suffix = getExtensionName(wareName).toLowerCase(Locale.ENGLISH);
		if (suffix.endsWith("pdf")) {
			response.setContentType("application/pdf;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("xlsx")) {
			response.setContentType("application/xlsx;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("docx")) {
			response.setContentType("application/docx;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("pptx")) {
			response.setContentType("application/pptx;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("xls")) {
			response.setContentType("application/xls;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("doc")) {
			response.setContentType("application/doc;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("ppt")) {
			response.setContentType("application/ppt;charset=utf-8"); // 设置返回的文件类型
		} else if (suffix.endsWith("rar")) {
			response.setContentType("application/rar;charset=utf-8"); // 设置返回的文件类型
		}else if (suffix.endsWith("zip")) {
			response.setContentType("application/zip;charset=utf-8"); // 设置返回的文件类型
		}else {
			throw new RuntimeException("错误的文件格式！");
		}
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ UrlCodeUtil.encode(wareName, "UTF-8"));

		return entity.getCourseware();
	}
	
	private static String getExtensionName(String filename){
		if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length() - 1))) {   
                return filename.substring(dot + 1);   
            }   
        }   
        return filename;
	}

}
